/*
 * Copyright (C),2015,北京新诺创科软件技术有限公司
 * author zhangmengliang
 */
package com.xnck.mfpms.controller;

import com.xnck.mfpms.annotation.Permission;
import com.xnck.mfpms.entity.ActionInfo;
import com.xnck.mfpms.entity.ResourceInfo;
import com.xnck.mfpms.entity.RoleInfo;
import com.xnck.mfpms.entity.UserInfo;
import com.xnck.mfpms.exception.ValidateException;
import com.xnck.mfpms.service.ActionService;
import com.xnck.mfpms.util.SessionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/sys/pms/action")
public class SysActionController extends BaseController{

    private static final Logger log = Logger.getLogger(SysActionController.class);

    @Autowired
    public ActionService actionService;

    /**
     * 权限列表
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_pms_action_list")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView getList(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView("/sys/pms/action/list");
        return mv;
    }

    /**
     * 权限总数
     * @param request
     * @param response
     * @param name
     */
    @Permission("url_sys_pms_action_list")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public void postList(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam(value = "name")String name,
                         @RequestParam(value = "parentid")String parentId){
        try {
            int count = actionService.getCount(name, parentId);
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e.toString());
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 权限主体
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_pms_action_listbody")
    @RequestMapping(value = "/listbody", method = RequestMethod.POST)
    public ModelAndView postBody(HttpServletRequest request, HttpServletResponse response,
                                 @RequestParam(value = "limit")int pageSize,
                                 @RequestParam(value = "offset")int beginIndex,
                                 @RequestParam(value = "name")String name,
                                 @RequestParam(value = "parentid")String parentId,
                                 @RequestParam(value = "sort", required = false)String orderName,
                                 @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/pms/action/listbody");
        try {
            List<ActionInfo> actions = actionService.gets(name, parentId, orderName, orderType, pageSize, beginIndex);
            mv.addObject("actions", actions);
        }
        catch (Exception e){
            log.error(e.toString());
        }
        return mv;
    }

    /**
     * 创建
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_pms_action_create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView getCreate(HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new ModelAndView("/sys/pms/action/create");
        return mv;
    }

    /**
     * 创建
     * @param request
     * @param response
     */
    @Permission("url_sys_pms_action_create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public void postCreate(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "displayname")String displayName,
                           @RequestParam(value = "parentid")String parentId,
                           @RequestParam(value = "remark")String remark,
                           @RequestParam(value = "enable", required = false)boolean enable){
        try {
            String curUserId = SessionUtils.getCurrentUserId(request);
            actionService.create(curUserId, displayName, parentId, remark, enable);
            responseSuccessMsg(response, null, "添加成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 修改
     * @param request
     * @param response
     * @return
     */
    @Permission("url_sys_pms_action_update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public ModelAndView getUpdate(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "id")String actionId){
        ModelAndView mv = new ModelAndView("/sys/pms/action/update");
        try {
            ActionInfo action = actionService.get(actionId);
            mv.addObject("action", action);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 修改资源
     * @param request
     * @param response
     */
    @Permission("url_sys_pms_action_update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public void postUpdate(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "id")String actionId,
                           @RequestParam(value = "displayname")String displayName,
                           @RequestParam(value = "parentid")String parentId,
                           @RequestParam(value = "remark")String remark,
                           @RequestParam(value = "enable", required = false)boolean enable){
        try {
            actionService.update(actionId, displayName, parentId, remark, enable);
            responseSuccessMsg(response, null, "修改成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 批量删除
     * @param request
     * @param response
     */
    @Permission("url_sys_pms_action_multidel")
    @RequestMapping(value = "/multidel", method = RequestMethod.POST)
    public void postMulti(HttpServletRequest request, HttpServletResponse response,
                          @RequestParam(value = "ids")String actionIds){
        try {
            actionService.deletes(actionIds);
            responseSuccessMsg(response, null, "删除成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 权限树子节点
     * @param request
     * @param response
     * @param parentId
     */
    @Permission("url_sys_pms_action_childs")
    @RequestMapping(value="/childs", method= RequestMethod.POST)
    public void postChilds(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value="id", required=false)String parentId){
        List<Map<String, Object>> chlids = new ArrayList<Map<String, Object>>();
        try {
            chlids = actionService.getNodesByPId(parentId);
        } catch (Exception e) {
            log.error(e.toString());
        }
        this.responseSuccessMsg(response, chlids, "ok");
    }

    /**
     * 权限树所有节点
     * @param request
     * @param response
     */
    @Permission("url_sys_pms_action_allchilds")
    @RequestMapping(value="/allchilds", method= RequestMethod.POST)
    public void postAllChilds(HttpServletRequest request, HttpServletResponse response){
        List<Map<String, Object>> chlids = new ArrayList<Map<String, Object>>();
        try {
            chlids = actionService.getAllNodes();
        } catch (Exception e) {
            log.error(e.toString());
        }
        this.responseSuccessMsg(response, chlids, "ok");
    }

    /**
     * 设置角色
     */
    @Permission("url_sys_pms_action_setrole")
    @RequestMapping(value = "/setrole", method = RequestMethod.GET)
    public ModelAndView getSetRole(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "id")String actionId){
        ModelAndView mv = new ModelAndView("/sys/pms/action/setrole");
        try {
            ActionInfo action = actionService.get(actionId);
            mv.addObject("action", action);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置角色
     */
    @Permission("url_sys_pms_action_setrole")
    @RequestMapping(value = "/setrole", method = RequestMethod.POST)
    public void postSetRole(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "aid")String actionId,
                            @RequestParam(value = "selflag", required = false)boolean isJoin,
                            @RequestParam(value = "ids")String roleIdStr){
        try {
            if (isJoin){
                actionService.cancelJoinRole(actionId, roleIdStr);
            }
            else {
                actionService.joinRole(actionId, roleIdStr);
            }
            responseSuccessMsg(response, null, "操作成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 角色列表总数
     */
    @Permission("url_sys_pms_action_rolelistcount")
    @RequestMapping(value = "/rolelistcount", method = RequestMethod.POST)
    public void postRoleList(HttpServletRequest request, HttpServletResponse response,
                             @RequestParam(value = "selflag", required = false)boolean isJoin,
                             @RequestParam(value = "name")String roleName,
                             @RequestParam(value = "aid")String actionId){
        try {
            int count;
            if (isJoin){
                count = actionService.getJoinedRolesCount(actionId, roleName);
            }
            else {
                count = actionService.getNoJoinRolesCount(actionId, roleName);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 角色列表主体
     */
    @Permission("url_sys_pms_action_rolelistbody")
    @RequestMapping(value = "/rolelistbody", method = RequestMethod.POST)
    public ModelAndView postRoleListBody(HttpServletRequest request, HttpServletResponse response,
                                         @RequestParam(value = "selflag", required = false)boolean isJoin,
                                         @RequestParam(value = "name")String roleName,
                                         @RequestParam(value = "aid")String actionId,
                                         @RequestParam(value = "limit")int pageSize,
                                         @RequestParam(value = "offset")int beginIndex,
                                         @RequestParam(value = "sort", required = false)String orderName,
                                         @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/pms/action/rolelistbody");
        try {
            List<RoleInfo> roles;
            if (isJoin){
                roles = actionService.getJoinedRoles(actionId, roleName,
                        orderName, orderType, pageSize, beginIndex);
            }
            else {
                roles = actionService.getNoJoinRoles(actionId, roleName,
                        orderName, orderType, pageSize, beginIndex);
            }

            mv.addObject("roles", roles);
            mv.addObject("selflag", isJoin);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }


    /**
     * 设置人员
     */
    @Permission("url_sys_pms_action_setuser")
    @RequestMapping(value = "/setuser", method = RequestMethod.GET)
    public ModelAndView getSetUser(HttpServletRequest request, HttpServletResponse response,
                                   @RequestParam(value = "id")String actionId){
        ModelAndView mv = new ModelAndView("/sys/pms/action/setuser");
        try {
            ActionInfo action = actionService.get(actionId);
            mv.addObject("action", action);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置人员
     */
    @Permission("url_sys_pms_action_setuser")
    @RequestMapping(value = "/setuser", method = RequestMethod.POST)
    public void postSetUser(HttpServletRequest request, HttpServletResponse response,
                            @RequestParam(value = "aid")String actionId,
                            @RequestParam(value = "selflag", required = false)boolean isJoin,
                            @RequestParam(value = "ids")String userIdStr){
        try {
            if (isJoin){
                actionService.cancelJoinUser(actionId, userIdStr);
            }
            else {
                actionService.joinUser(actionId, userIdStr);
            }
            responseSuccessMsg(response, null, "操作成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 人员列表总数
     */
    @Permission("url_sys_pms_action_userlistcount")
    @RequestMapping(value = "/userlistcount", method = RequestMethod.POST)
    public void postUserListCount(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "selflag", required = false)boolean isJoin,
                                  @RequestParam(value = "name")String userName,
                                  @RequestParam(value = "aid")String actionId){
        try {
            int count;
            if (isJoin){
                count = actionService.getJoinedUsersCount(actionId, userName);
            }
            else {
                count = actionService.getNoJoinUsersCount(actionId, userName);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 人员列表主体
     */
    @Permission("url_sys_pms_action_userlistbody")
    @RequestMapping(value = "/userlistbody", method = RequestMethod.POST)
    public ModelAndView postUserListBody(HttpServletRequest request, HttpServletResponse response,
                                         @RequestParam(value = "selflag", required = false)boolean isJoin,
                                         @RequestParam(value = "name")String userName,
                                         @RequestParam(value = "aid")String actionId,
                                         @RequestParam(value = "limit")int pageSize,
                                         @RequestParam(value = "offset")int beginIndex,
                                         @RequestParam(value = "sort", required = false)String orderName,
                                         @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/pms/action/userlistbody");
        try {
            List<UserInfo> users;
            if (isJoin){
                users = actionService.getJoinedUsers(actionId, userName,
                        orderName, orderType, pageSize, beginIndex);
            }
            else {
                users = actionService.getNoJoinUsers(actionId, userName,
                        orderName, orderType, pageSize, beginIndex);
            }

            mv.addObject("users", users);
            mv.addObject("selflag", isJoin);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置资源
     */
    @Permission("url_sys_pms_action_setres")
    @RequestMapping(value = "/setres", method = RequestMethod.GET)
    public ModelAndView getSetRes(HttpServletRequest request, HttpServletResponse response,
                                  @RequestParam(value = "id")String actionId){
        ModelAndView mv = new ModelAndView("/sys/pms/action/setres");
        try {
            ActionInfo action = actionService.get(actionId);
            mv.addObject("action", action);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }

    /**
     * 设置资源
     */
    @Permission("url_sys_pms_action_setres")
    @RequestMapping(value = "/setres", method = RequestMethod.POST)
    public void postSetRes(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "aid")String actionId,
                           @RequestParam(value = "selflag", required = false)boolean isJoin,
                           @RequestParam(value = "ids")String resIdStr){
        try {
            if (isJoin){
                actionService.cancelJoinRes(actionId, resIdStr);
            }
            else {
                actionService.joinRes(actionId, resIdStr);
            }
            responseSuccessMsg(response, null, "操作成功");
        }
        catch (ValidateException ve){
            log.error(ve);
            responseErrorMsg(response, ve.getMessage());
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部异常");
        }
    }

    /**
     * 资源列表总数
     */
    @Permission("url_sys_pms_action_reslistcount")
    @RequestMapping(value = "/reslistcount", method = RequestMethod.POST)
    public void postResListCount(HttpServletRequest request, HttpServletResponse response,
                                 @RequestParam(value = "selflag", required = false)boolean isJoin,
                                 @RequestParam(value = "name")String resName,
                                 @RequestParam(value = "aid")String actionId){
        try {
            int count;
            if (isJoin){
                count = actionService.getJoinedResCount(actionId, resName);
            }
            else {
                count = actionService.getNoJoinResCount(actionId, resName);
            }
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("count", count);
            responseSuccessMsg(response, map, "OK");
        }
        catch (Exception e){
            log.error(e);
            responseErrorMsg(response, "内部错误");
        }
    }

    /**
     * 资源列表主体
     */
    @Permission("url_sys_pms_action_reslistbody")
    @RequestMapping(value = "/reslistbody", method = RequestMethod.POST)
    public ModelAndView postResListBody(HttpServletRequest request, HttpServletResponse response,
                                        @RequestParam(value = "selflag", required = false)boolean isJoin,
                                        @RequestParam(value = "name")String resName,
                                        @RequestParam(value = "aid")String actionId,
                                        @RequestParam(value = "limit")int pageSize,
                                        @RequestParam(value = "offset")int beginIndex,
                                        @RequestParam(value = "sort", required = false)String orderName,
                                        @RequestParam(value = "order", required = false)String orderType){
        ModelAndView mv = new ModelAndView("/sys/pms/action/reslistbody");
        try {
            List<ResourceInfo> reses;
            if (isJoin){
                reses = actionService.getJoinedRes(actionId, resName,
                        orderName, orderType, pageSize, beginIndex);
            }
            else {
                reses = actionService.getNoJoinRes(actionId, resName,
                        orderName, orderType, pageSize, beginIndex);
            }

            mv.addObject("reses", reses);
            mv.addObject("selflag", isJoin);
        }
        catch (Exception e){
            log.error(e);
        }
        return mv;
    }
}
